package com.zj.osm.view.map.map;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.location_library.china_location.ChinaLocation;
import com.example.location_library.china_location.ChinaLocationNotifyChange;
import com.example.location_library.china_location.ChineLocationBean;
import com.example.location_library.china_location.GCJ2WGS;
import com.example.location_library.china_location.LocationType;
import com.google.android.gms.maps.model.LatLng;
import com.zj.osm.App;
import com.zj.osm.R;
import com.zj.osm.adapter.TDialogReAdapter;
import com.zj.osm.bean.AddMarkerAndLine;
import com.zj.osm.bean.PointNode;
import com.zj.osm.entity.db.EquipmentDao;
import com.zj.osm.entity.db.LineDao;
import com.zj.osm.entity.db.PointDao;
import com.zj.osm.entity.greendao.Equipment;
import com.zj.osm.entity.greendao.Line;
import com.zj.osm.entity.greendao.Point;
import com.zj.osm.entity.greendao.Project;
import com.zj.osm.mvp.MvpActivity;
import com.zj.osm.utils.ThreadManager;
import com.zj.osm.utils.ThreeUtils;
import com.zj.osm.utils.db_utils.LineUtils;
import com.zj.osm.utils.db_utils.PointsUtils;
import com.zj.osm.view.map.line.DistanceActivity;
import com.zj.osm.view.map.line.LineActivity;
import com.zj.osm.view.map.offline.OfflineMapActivity;
import com.zj.osm.view.project.projectdetail.ProjectDetailActivity;
import com.zj.utils.data.LiveDataBus;
import com.zj.utils.emm.EquipmentCateGoryEmm;
import com.zj.utils.map.GoogleTileSource;
import com.zj.utils.map.LineInfoWindow;
import com.zj.utils.map.MapUtils;
import com.zj.utils.map.MarkerWindow;
import com.zj.utils.utils.utilcode.SPUtils;
import com.zj.utils.utils.utilcode.ToastUtils;
import com.zj.utils.view.PopupMenu;
import com.zj.utils.view.TitleBar;

import org.jetbrains.annotations.NotNull;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.api.IMapController;
import org.osmdroid.config.Configuration;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.tileprovider.modules.OfflineTileProvider;
import org.osmdroid.tileprovider.util.SimpleRegisterReceiver;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.CustomZoomButtonsController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.Marker;
import org.osmdroid.views.overlay.MinimapOverlay;
import org.osmdroid.views.overlay.OverlayWithIW;
import org.osmdroid.views.overlay.Polyline;
import org.osmdroid.views.overlay.compass.CompassOverlay;
import org.osmdroid.views.overlay.compass.InternalCompassOrientationProvider;
import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider;
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static com.zj.osm.App.getInstances;
import static com.zj.osm.utils.Configuration.MAP_TILE_SOURCE;
import static com.zj.osm.utils.Configuration.PROJECT_ID;
import static com.zj.osm.utils.MyUtils.Distance;
import static com.zj.osm.utils.MyUtils.bearing;
import static com.zj.osm.utils.ThreadManager.getThreadPool;

public class MapActivity extends MvpActivity<MapActivityView, MapActivityPresenter> implements EasyPermissions.PermissionCallbacks, View.OnClickListener, MapActivityView, LocationListener, ChinaLocationNotifyChange {
    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

    public static boolean isProgressShow = true;
    private static final int MIN_ADD_MARKER_DISTANCE = 5;
    private static final int TEXT_LABEL_FONT_SIZE = 40;
    private static final float MARKER_ANCHOR_V = 2.2f;
    private static String MAIN_ADD_TOWER = "杆塔";
    private static String MAIN_ADD_TERRAIN = "地形点";
    //private boolean IS_WITH_LEVER = false;//是否同杆并架（状态 false为否）
    private boolean CHOOSE_POINT = false; //选择点
    //拉直线用来记录状态
    private boolean CHOOSE_PINTZX = false;
    private boolean WHETHER_CONNECTION = false;//是否连接连点（状态 false为否）
    private boolean WHETHER_TO_SHOW_GUIDES = true;//是否显示辅助勘测线（状态 默认为true为显示）
    private boolean WHETHER_TO_DISPLAY_THE_NUMBER = false;//是否显示编号
    private boolean WHETHER_TO_DISPLAY_THE_PITCH = false;//是否显示档距
    private MapView mMapView;
    private Polyline mPolyline;//显示当前位置距离上一点的距离的线
    private MyLocationNewOverlay mLocationOverlay;//自己当前所在位置
    private TextView mainTvLength;//显示当前位置距离上一点的距离的线
    private IMapController mapController;
    private Project project;//当前项目
    private List<Point> pointList = new ArrayList<>();
    private TitleBar mainTitleBar;
    private List<Double> latList = new LinkedList<>();
    private List<Double> longList = new LinkedList<>();
    private List<Line> parallelPoleList = new ArrayList<>();//同杆并架线的集合
    private List<Polyline> parallelWithBarList = new ArrayList<>();//同杆并架线图层
    private List<String> withTheLeverList = new ArrayList<>();//同杆并架的暂时存储位置（里面放的是需要同杆并假点的id）
    private List<String> connectionLine = new ArrayList<>();//两点连接的暂时存储位置（里面放的是需要同杆并假点的id）
    private List<Marker> markerLinkedList = new LinkedList<>();//勘察点图层
    private List<Marker> markerNameLinkedList = new LinkedList<>();//勘察点名称图层
    private List<Marker> markerEquipList = new LinkedList<>();//柱上设备和杆高
    private List<Polyline> polylineLinkedList = new LinkedList<>(); //线路图层
    private List<Marker> polylineLengthLinkedList = new LinkedList<>();//线路档距图层
    private OverlayWithIW overlay;//当前显示InfoWindow的覆盖物
    private IGeoPoint mapCenter;//屏幕中心点坐标接口
    private GeoPoint point;//屏幕中心点坐标
    private TextView mainTitlBarRightTv;
    private CustomZoomButtonsController zoomController;
    private Button mapState;
    private LocationManager locationManager;
    private Location useLocation;
    private Button mMapVisibleAllPointBt;
    //连线模式
    private boolean ConnectEquipModel;
    private Context context;
    //是否T分阶。0表示点击杆塔。1表示点击T分接，2表示点击继续勘测
    private int isTfenjieState = 0;
    //是否显示档距
    private boolean btn_Length_isCheck = false;
    //海拔
    private double high = 0;
    private String address = "";
    //最后一个有效勘察点，用于构建辅助线
    private Marker currentMarker;
    //当前点
    private Point crrentMartPoints;
    //线上面的marker用来判断弹窗
    private Marker lineTopMarker;
    //线下面的marker用来判断弹窗
    private Marker lineDownMarker;
    private boolean jixukance;
    private Button mVisibleAllBt;
    private Button mVisibleSpanBt;
    private Point latLngList;
    private List<View> viewList = new ArrayList<>();//存储Marker弹窗的view
    private Marker ConnectMarker = null;
    private Point jpoints;
    private TextView activity_tv_quxiao;
    private TextView activity_tv_save;
    private ImageView iv_center;
    private Button mainBtnTerrain;
    private ImageButton main_gonjin;
    private Button mainBtnFacility;
    private Button mainBtnTower;
    private Button map_btn_four;
    private ProgressDialog mProgressDialog;
    private Button two_local, two_online;
    private MinimapOverlay mMinimapOverlay;
    private String tLineId = "";
    private Double maxDistance = 0.0;
    private TextView mainTvAngle;
    private boolean locationType = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        Context ctx = getApplicationContext();
        Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
        setContentView(R.layout.activity_map);
        initView();
        loadMap();
        initData();
    }

    /**
     * 加载地图
     */
    @SuppressLint({"SetTextI18n", "DefaultLocale", "MissingPermission"})
    private void initMap() {
        //设置地图源
        setMapSources();
        mapController = mMapView.getController();
        mapController.setZoom(18.0);
        this.mLocationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(this), mMapView);
        this.mLocationOverlay.enableMyLocation();
        /**
         *设置跟随 不设置会导致if (mLocationOverlay != null && mLocationOverlay.mMyLocationProvider != null && mLocationOverlay.mMyLocationProvider.getLastKnownLocation() != null) {
         * this.mLocationOverlay.setEnableAutoStop(true);//不让自动滚动UI
         * this.mLocationOverlay.enableMyLocation();
         * this.mLocationOverlay.enableFollowLocation();
         */
//        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
//        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
        //定位自己
        ChinaLocation.getInstance().setContext(this).setLocationType(LocationType.GAO_DE).initLocation();
        CompassOverlay mCompassOverlay = new CompassOverlay(this, new InternalCompassOrientationProvider(this), mMapView);
        mCompassOverlay.enableCompass();
        mMapView.getOverlays().add(mCompassOverlay);
        //缩放按钮
        mMapView.setBuiltInZoomControls(false);
        mMapView.setMultiTouchControls(true);

        Button mapBlodUp = findViewById(R.id.mapBlodUp);
        Button mapBlodDown = findViewById(R.id.mapBlodDown);
        mapBlodUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("maxSize=", (mMapView.getZoomLevel() + 1) + "");
                mapController.setZoom(mMapView.getZoomLevel() + 1);
            }
        });
        mapBlodDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mapController.setZoom(mMapView.getZoomLevel() - 1);
            }
        });
        mMapView.setMaxZoomLevel(23.0);
        mMinimapOverlay = new MinimapOverlay(this, mMapView.getTileRequestCompleteHandler());
        mMinimapOverlay.setWidth(getScrreen().widthPixels / 5);
        mMinimapOverlay.setHeight(getScrreen().widthPixels / 5);
        mMapView.getOverlays().add(mMinimapOverlay);
        mMapView.addMapListener(new MapListener() {
            @Override
            public boolean onScroll(ScrollEvent event) {
                return false;
            }

            @Override
            public boolean onZoom(ZoomEvent event) {
                /*if (!parallelPoleList.isEmpty())
                    drawParallelWithBar();*/
                return false;
            }
        });

        List<GeoPoint> geoPointListCenter = new ArrayList<>();
        mMapView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View v) {

            }

            @Override
            public void onViewDetachedFromWindow(View v) {

            }
        });
        mMapView.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
            if (WHETHER_TO_SHOW_GUIDES) {//是否显示辅助线开关
                if (pointList.size() > 0) {
                    mainTvLength.setVisibility(View.VISIBLE);
                    geoPointListCenter.clear();
                    if (currentMarker == null) {
                        return;
                    }
                    if (currentMarker.getId() != null) {
                        String pointId = currentMarker.getId();
//                        Point point = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(pointId)).unique();
                        Point point =(Point) currentMarker.getRelatedObject();
                        geoPointListCenter.add(new GeoPoint(point.getLatitude(), point.getLongitude()));
//                        Log.e("ppp.toStingwf=", point.toString1());
                        geoPointListCenter.add(new GeoPoint(point.getLatitude(), point.getLongitude()));
                        double lenght = MapUtils.distance(mapCenter.getLatitude(), mapCenter.getLongitude(), point.getLatitude(), point.getLongitude());
                        mainTvLength.setText(String.format("%.2f", lenght) + "米");
                        ///获取角度知道三条线段然后求角度。
                        Point centernPoint = new Point();
                        centernPoint.setLatitude(mapCenter.getLatitude());
                        centernPoint.setLongitude(mapCenter.getLongitude());
                        double jiaodu = LineUtils.getLineLenthAndAngle(point, centernPoint, lenght);
                        mainTvAngle.setText((jiaodu + "°").replace("NaN", "0.0"));
                    } else {
                        geoPointListCenter.add(new GeoPoint(pointList.get(pointList.size() - 1).getLatitude(), pointList.get(pointList.size() - 1).getLongitude()));
                        mainTvLength.setText(String.format("%.2f", MapUtils.distance(mapCenter.getLatitude(), mapCenter.getLongitude(), pointList.get(pointList.size() - 1).getLatitude(), pointList.get(pointList.size() - 1).getLongitude())) + "米");
                    }
                    //距离
                    if (useLocation != null && useLocation.getLatitude() > 0) {
                        //userLocation是客户所在位置
                        maxDistance = MapUtils.distance(mapCenter.getLatitude(), mapCenter.getLongitude(), useLocation.getLatitude(), useLocation.getLongitude());
                        if (maxDistance > 1000) {
                            ToastUtils.showShort("你已经超出1公里项目范围");
                        }
                    }

                    //计算夹角
                    //mainTvAngle
                    mapCenter = mMapView.getMapCenter();
                    point = new GeoPoint(mapCenter.getLatitude(), mapCenter.getLongitude());
                    geoPointListCenter.add(point);
                    mMapView.getOverlays().remove(mPolyline);
                    mPolyline = new Polyline();
                    mPolyline.setPoints(geoPointListCenter);
                    mPolyline.setColor(Color.argb(160, 99, 189, 148));
                    mPolyline.setWidth(6);
                    mPolyline.setGeodesic(false);
                    mPolyline.getPaint().setPathEffect(new DashPathEffect(new float[]{22, 22}, 22));
                    mMapView.getOverlays().add(mPolyline);
                }
            } else {
                mainTvLength.setVisibility(View.GONE);
                mMapView.getOverlays().remove(mPolyline);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mMinimapOverlay != null) {
            mMinimapOverlay.onResume();
        }
        createProgressDialog();
        if (mMapView != null) {
            mMapView.onResume(); //needed for compass, my location overlays, v6.0.0 and up
            mMapView.getOverlays().clear();
            ///给宝哥专做的
            /*double latitude = 26.069989;//119.310198    26.069989
            double longitude = 119.310198;
            mapController = mMapView.getController();
            GeoPoint enen = new GeoPoint(latitude, longitude);
            //动画平移到当前位置
            mapController.animateTo(enen, 10.402410327398883, 100L);*/
        }
        initData();
        //切换地图后进行刷新
        setMapSources();
        Message msg = mHandler.obtainMessage();
        msg.what = 1;
        mHandler.sendMessageDelayed(msg, 300);

    }

    @Override
    protected void onStop() {
        super.onStop();
        App.getInstances().btn_model = true;
        Log.e("llll=", mMapView.getZoomLevelDouble() + "");
    }

    /**
     * 加载地图的流程
     * 安卓6.0以上需要线请求权限
     */
    private void loadMap() {
        if (Build.VERSION.SDK_INT >= 23) {
            showContacts();
        } else {
            //定位，加载地图
            initMap();
        }
    }

    @Override
    public MapActivityPresenter createPresenter() {
        return new MapActivityPresenter();
    }

    @Override
    public MapActivityView createView() {
        return this;
    }

    /**
     * 加载数据
     */
    private void initData() {
        LiveDataBus.get().getChannel(PROJECT_ID, Long.class).observe(this, projectId -> getPresenter().initPointAndLine(projectId));
    }

    AlertDialog dialogFushu;
    RecyclerView dialogRv;
    Button mapTfzBt;
    Button mapTfzBtCancel;

    private void initView() {
        //显示柱上设备模态弹窗
        final View views = View.inflate(context, R.layout.activity_tfz_dialog_layout, null);
        dialogRv = views.findViewById(R.id.mVList);
        mapTfzBt = views.findViewById(R.id.mapTfzBt);
        mapTfzBtCancel = views.findViewById(R.id.mapTfzBtCancel);
        dialogFushu = new AlertDialog.Builder(context).create();
        dialogFushu.setView(views);
        activity_tv_quxiao = findViewById(R.id.activity_tv_quxiao);
        activity_tv_save = findViewById(R.id.activity_tv_save);
        iv_center = findViewById(R.id.mainIvCenter);
        map_btn_four = findViewById(R.id.map_btn_four);
        mMapVisibleAllPointBt = findViewById(R.id.map_viewAll);
        mMapVisibleAllPointBt.setOnClickListener(this);
        mVisibleAllBt = findViewById(R.id.map_btn_name);
        mVisibleSpanBt = findViewById(R.id.map_btn_length);
        mMapView = findViewById(R.id.map);
        mapState = findViewById(R.id.map_btn_model);
        Button mapFuzhuButton = findViewById(R.id.map_open_line);
        mapFuzhuButton.setOnClickListener(this);
        mapState.setOnClickListener(this);
        mVisibleAllBt.setOnClickListener(this);
        mVisibleSpanBt.setOnClickListener(this);
        mainBtnTower = findViewById(R.id.mainBtnTower);
        mainBtnTower.setOnClickListener(this);
        ImageButton mainIbLocation = findViewById(R.id.mainIbLocation);
        mainIbLocation.setOnClickListener(this);
        mainTvLength = findViewById(R.id.mainTvLength);
        mainTvAngle = findViewById(R.id.mainTvAngle);
        mainTitleBar = findViewById(R.id.mainTitleBar);
        mainTitleBar.setRightText("更多");
        mainTitleBar.setBackImageVisiable(true);
        mainBtnTerrain = findViewById(R.id.mainBtnTerrain);
        mainBtnTerrain.setOnClickListener(this);
        //main_gonjin
        main_gonjin = findViewById(R.id.main_gonjin);
        main_gonjin.setOnClickListener(this);
        mainBtnFacility = findViewById(R.id.mainBtnFacility);
        mainBtnFacility.setOnClickListener(this);
        mainTitleBar.setRightTextOnClickListener(v -> {
            PopupMenu popupMenu = new PopupMenu(this);
            popupMenu.setPopView(R.layout.layout_popup_menu);
            //地图切换
            popupMenu.setPopupOnClickListener(R.id.ly_item1, v1 -> {
                popupMenu.dismiss();
                startIntent(OfflineMapActivity.class);
                //startIntent(SetMapSourceActivity.class);
            });
            //项目详情
            popupMenu.setPopupOnClickListener(R.id.ly_item2, v1 -> {
                popupMenu.dismiss();
                Bundle bundle = new Bundle();
                bundle.putLong(PROJECT_ID, project.getId());
                startIntent(ProjectDetailActivity.class, bundle);
            });
           /*//辅助勘测
            popupMenu.setPopupOnClickListener(R.id.ly_item3, v1 -> {
                popupMenu.dismiss();
                WHETHER_TO_SHOW_GUIDES = !WHETHER_TO_SHOW_GUIDES;
            });
            //显示所有
            popupMenu.setPopupOnClickListener(R.id.ly_item6, v1 -> {
                popupMenu.dismiss();
                //将地图中心点移动到所有点的中心
                if (!latList.isEmpty() && !longList.isEmpty()) {
                    getPresenter().toPointsLocation(latList, longList);
                }
            });*/
        });
        two_local = findViewById(R.id.two_local);
        two_local.setOnClickListener(this);
        two_online = findViewById(R.id.two_online);
        two_online.setOnClickListener(this);

    }


    /**
     * 画同杆并架的线
     *
     * @param pointsFist 点
     * @param addNum     偏移经纬度
     * @param degrees    两点之间角度
     * @param methodName 向上还是向下偏移
     */
    private void addTongGanNewLine(Point pointsFist, Point endPoints, Double addNum, double degrees, int methodName) {
        Line line = LineUtils.getInstance().getTongGanNewLine(pointsFist, endPoints, addNum, degrees, methodName, project);
        getInstances().getDaoSession().getLineDao().insert(line);
        drawMyRoute(line);

    }

    private List<Point> lstTempPoints = new ArrayList<>();


    public static List<String> paths = new ArrayList<>(); //定义保存路径的数组

    public static void FindAllPaths(PointNode treeNodes, String target, String path) {
        path += treeNodes.getNode().getUid() + "|";
        if (treeNodes.getNode().getUid().equals(target)) {
            String leafPath = path;
            Log.e("leafpath", leafPath);
            paths.add(leafPath);
        }

        if (treeNodes == null
                || treeNodes.getChilderNodeList() == null) {
            return;
        }

        for (int i = 0, len = treeNodes.getChilderNodeList().size(); i < len; i++) {
            FindAllPaths(treeNodes.getChilderNodeList().get(i), target, path);
        }
    }

    /**
     * wangfei
     * 拉直所有节点线
     *
     * @param marker /
     */
    private void createCircuitZhiLine(Marker marker) {
        Point pointsFist = (Point) marker.getRelatedObject();
        if (pointsFist.getUid().equals(latLngList.getUid())) {
            com.blankj.utilcode.util.ToastUtils.showShort("不能选择已选杆塔");
        } else {
            CHOOSE_PINTZX = false;
            //获取到要拉直的所有的点。
            List<Point> resultPoints = getAllNodeBettwenSE(latLngList, pointsFist);
            if (resultPoints.size() > 2) {
                final View views = View.inflate(context, R.layout.activity_map_dialog, null);
                AlertDialog dialog = new AlertDialog.Builder(context).create();
                TextView map_tv_title = views.findViewById(R.id.map_tv_title);
                TextView map_tv_content = views.findViewById(R.id.map_tv_content);
                Button map_btn_quxiao = views.findViewById(R.id.map_btn_quxiao);
                Button map_btn_queding = views.findViewById(R.id.map_btn_queding);
                map_tv_title.setText("线路矫正");
                map_tv_content.setText("确定矫正线路？");
                dialog.setView(views);
                dialog.show();
                map_btn_queding.setOnClickListener(view12 -> {
                    ///拿到来所有的点。
                    for (int i = 1; i < resultPoints.size() - 1; i++) {
                        //3。删除点。
                        remove(markerLinkedList, resultPoints.get(i).getUid());
                        //删除点marker图片和marker上下的文字和住上设备
                        remove(markerNameLinkedList, resultPoints.get(i).getUid());
                        //删除柱上设备
                        remove(markerEquipList, resultPoints.get(i).getUid());
                        Point resultPoingss = LineUtils.getProjectivePoint(resultPoints.get(0), resultPoints.get(resultPoints.size() - 1), resultPoints.get(i));
                        resultPoints.get(i).setLatitude(resultPoingss.getLatitude());
                        resultPoints.get(i).setLongitude(resultPoingss.getLongitude());
                        getInstances().getDaoSession().getPointDao().update(resultPoints.get(i));
                        //第一个点获取到了。这个作为 pointsfist.
                        List<Line> relateLines = getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.Start_id.eq(resultPoints.get(i).getUid()), LineDao.Properties.End_id.eq(resultPoints.get(i).getUid())).build().list();
                        for (Line l : relateLines) {
                            //fist第一次点的需要移动的点。
                            //lat是需要去的地方。
                            //1。删除地图上线档距和类型
                            remove(polylineLengthLinkedList, l.getId().toString());
                            //2。这个移除线。
                            removeLinePoline(l);
                            if (l.getStart_id().equals(resultPoints.get(i).getUid())) {
                                l.setLatA(resultPoints.get(i).getLatitude().toString());
                                l.setLonA(resultPoints.get(i).getLongitude().toString());
                                BigDecimal bg = new BigDecimal(Distance(Double.valueOf(l.getLatB()), Double.valueOf(l.getLonB()), Double.valueOf(l.getLatA()), Double.valueOf(l.getLonA()))).setScale(2, RoundingMode.UP);
                                l.setLength(bg.doubleValue() + "");
                                getInstances().getDaoSession().getLineDao().update(l);

                            } else if (l.getEnd_id().equals(resultPoints.get(i).getUid())) {
                                l.setLatB(resultPoints.get(i).getLatitude().toString());
                                l.setLonB(resultPoints.get(i).getLongitude().toString());
                                BigDecimal bg = new BigDecimal(Distance(Double.valueOf(l.getLatB()), Double.valueOf(l.getLonB()), Double.valueOf(l.getLatA()), Double.valueOf(l.getLonA()))).setScale(2, RoundingMode.UP);
                                l.setLength(bg.doubleValue() + "");
                                getInstances().getDaoSession().getLineDao().update(l);
                            }
                        }
                    }
                    initData();
                    dialog.dismiss();

                });
                map_btn_quxiao.setOnClickListener(view1 -> {
                    CHOOSE_PINTZX = false;
                    dialog.dismiss();
                });
            } else {
                ToastUtils.showShort("就在同一直线上");
            }
        }


    }

    void removeLinePoline(Line line) {
        for (int j = 0; j < polylineLinkedList.size(); j++) {
            Polyline nowLine = (polylineLinkedList.get(j));
            Line ploline = (Line) nowLine.getRelatedObject();
            if (ploline.equals(line)) {
                //删除集合中的线图层
                polylineLinkedList.remove(nowLine);
                //删除地图上点图层
                mMapView.getOverlays().remove(nowLine);
            }

        }
    }

    private MarkerWindow mapViewWindow;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                //若工作完成，取消动画，初始化界面
                if (mProgressDialog != null) {
                    mProgressDialog.cancel();
                }
            }
        }
    };
    /**
     * 线程
     */
    private Runnable mRunnable = () -> {
        //需要耗时的工作
        //initData();
        Message msg = mHandler.obtainMessage();
        msg.what = 1;
        mHandler.sendMessage(msg);
    };

    /**
     * marker点击事件
     *
     * @param marker 点
     */
    private void clickMarker(Marker marker) {
        Point pointsFist = (Point) marker.getRelatedObject();
        /*View view = View.inflate(context, R.layout.activity_map_info, null);
        IGeoPoint iGeoPoint=new GeoPoint(pointsFist.getLatitude(),pointsFist.getLongitude());
        ViewGroup.LayoutParams params = new MapView.LayoutParams(MapView.LayoutParams.WRAP_CONTENT,MapView.LayoutParams.WRAP_CONTENT,iGeoPoint,TOP_RIGHT,0,1);
        mMapView.addView(view,params);
       */
        MarkerWindow popWindowView = new MarkerWindow(R.layout.activity_map_info, mMapView);
        mapViewWindow = popWindowView;
        //showInfoWindow(marker, popWindowView, 0);
        TextView xiugai = popWindowView.getView().findViewById(R.id.map_tv_xiugai);
        TextView yidong = popWindowView.getView().findViewById(R.id.map_tv_yidong);
        TextView shanchu = popWindowView.getView().findViewById(R.id.map_tv_shanchu);
        TextView quxiao = popWindowView.getView().findViewById(R.id.map_tv_quxiao);
        LinearLayout tonggan = popWindowView.getView().findViewById(R.id.map_tv_tgbj);
        TextView kance = popWindowView.getView().findViewById(R.id.map_tv_kance);
        TextView jixuKanceTv = popWindowView.getView().findViewById(R.id.map_tv_continue);
        View view_line = popWindowView.getView().findViewById(R.id.map_view_kance);
        View jixukanchaLine = popWindowView.getView().findViewById(R.id.map_view_delete_all);
        View tonggan_line = popWindowView.getView().findViewById(R.id.map_view_tgbj);
        View jixuEndView = popWindowView.getView().findViewById(R.id.jixuEndView);
        TextView map_tv_lianjie = popWindowView.getView().findViewById(R.id.map_tv_lianjie);
        TextView map_tv_jiaozheng = popWindowView.getView().findViewById(R.id.map_tv_jiaozheng);
        LinearLayout xiahu_layout = popWindowView.getView().findViewById(R.id.xiahu_layout);
        TextView map_tv_xiahu = popWindowView.getView().findViewById(R.id.map_tv_xiahu);
        if (pointsFist.getName().contains("地形点")) {
            kance.setVisibility(View.GONE);
            if (pointsFist.getEquipType_name() != null && !pointsFist.getEquipType_name().contains("拐点") && !pointsFist.getEquipType_name().contains("连接点")) {
                jixuKanceTv.setVisibility(View.GONE);
                map_tv_lianjie.setVisibility(View.GONE);
                tonggan_line.setVisibility(View.GONE);
                jixuEndView.setVisibility(View.GONE);
            } else {
                tonggan_line.setVisibility(View.VISIBLE);
            }
        }
        if (pointsFist.getIsT() == null || pointsFist.getIsT().isEmpty() || pointsFist.getIsT().equals("0")) {//默认0隐藏不选择分支
            jixukanchaLine.setVisibility(View.GONE);
        }
        //继续勘测的问题。
        //1。如果端头一定可以看见。
        //这里判断如果线不是T线且连点有2条那么就隐藏其他的可以进行显示。
        List<Point> allguanLianPoints = new ArrayList<>();
        List<Line> allguanLian = getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.Start_id.eq(pointsFist.getUid()), LineDao.Properties.End_id.eq(pointsFist.getUid())).list();
        for (int i = 0; i < allguanLian.size(); i++) {
            List<Point> pointLists = getInstances().getDaoSession().getPointDao().queryBuilder().whereOr(PointDao.Properties.Uid.eq(allguanLian.get(i).getStart_id()), PointDao.Properties.Uid.eq(allguanLian.get(i).getEnd_id())).list();
            allguanLianPoints.addAll(pointLists);
        }
        allguanLianPoints = new ArrayList(new HashSet(allguanLianPoints));

        if (allguanLianPoints.size() == 2) {//如果是有切只有一个关联点那么一定可以继续勘测。
            jixuKanceTv.setVisibility(View.VISIBLE);
            jixukanchaLine.setVisibility(View.VISIBLE);

        } else if (allguanLianPoints.size() > 2) {
            List<Line> allGuanlianLine = getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.Start_id.eq(pointsFist.getUid()), LineDao.Properties.End_id.eq(pointsFist.getUid())).whereOr(LineDao.Properties.ParallelPole.isNull(), LineDao.Properties.ParallelPole.eq("0"), LineDao.Properties.ParallelPole.eq("同杆并架")).list();
            List<Line> unitqGuanlianLine = new ArrayList<>();
            List<String> unitqGuanlianLineName = new ArrayList<>();
            List<Line> gulianLine = new ArrayList<>();
            for (int i = 0; i < allGuanlianLine.size(); i++) {
                if (unitqGuanlianLineName.contains(allGuanlianLine.get(i).getName())) {
                    unitqGuanlianLineName.remove(allGuanlianLine.get(i).getName());
                    for (int j = 0; j < unitqGuanlianLine.size(); j++) {
                        if (unitqGuanlianLine.get(j).getName().equals(allGuanlianLine.get(i).getName())) {
                            unitqGuanlianLine.remove(unitqGuanlianLine.get(j));
                        }
                    }
                } else {
                    unitqGuanlianLineName.add(allGuanlianLine.get(i).getName());
                    unitqGuanlianLine.add(allGuanlianLine.get(i));
                }
            }
            unitqGuanlianLineName.clear();
            gulianLine.clear();
            gulianLine.addAll(unitqGuanlianLine);
            if (gulianLine.size() <= 0 && (pointsFist.getName().equals("杆塔") || pointsFist.getName().equals("地形点"))) {
                jixuKanceTv.setVisibility(View.GONE);
                jixukanchaLine.setVisibility(View.GONE);
            } else {
                jixukanchaLine.setVisibility(View.VISIBLE);
            }


        }
        if (pointsFist.getName().contains("杆塔")) {
            tonggan.setVisibility(View.VISIBLE);
            tonggan_line.setVisibility(View.VISIBLE);
            xiahu_layout.setVisibility(View.VISIBLE);
        }
        if (pointsFist.getIsT() == null || pointsFist.getIsT().isEmpty() || pointsFist.getIsT().equals("0")) {//默认0隐藏不选择分支
            kance.setVisibility(View.GONE);
            tonggan_line.setVisibility(View.GONE);

        }
        showInfoWindow(marker, popWindowView, 0);
        tonggan.setOnClickListener(v -> {
            showInfoWindow(marker, popWindowView, 1);
            CHOOSE_POINT = true;
            CHOOSE_PINTZX = false;
            latLngList = pointsFist;
            ToastUtils.showShort("请选择另外一个点");
        });
        map_tv_jiaozheng.setOnClickListener(v -> {
            showInfoWindow(marker, popWindowView, 1);
            CHOOSE_PINTZX = true;
            CHOOSE_POINT = false;
            latLngList = pointsFist;
            ToastUtils.showShort("请选择另外一个点");
        });

        map_tv_xiahu.setOnClickListener(v -> {
            showInfoWindow(marker, popWindowView, 1);
            jixukance = true;
            jpoints = pointsFist;
            currentMarker = marker;
            isTfenjieState = 0;
            //修改线对应的关联关系吧？
            creatPolyline(WHETHER_TO_SHOW_GUIDES);
        });
        //连线操作
        if (ConnectEquipModel) {
            showInfoWindow(marker, popWindowView, 1);
            //mMapView.removeView(view);
            if (ConnectMarker == marker) {
                ConnectEquipModel = false;
                ToastUtils.showShort("不能连接自己");
                return;
            }

            ConnectTowEquip(ConnectMarker, marker);
        }
        map_tv_lianjie.setOnClickListener(v -> {
            showInfoWindow(marker, popWindowView, 1);
            //移除ToolMenu
            //mMapView.removeView(view);
            com.blankj.utilcode.util.ToastUtils.showShort("请选择需要连接的杆塔或设备");
            ConnectEquipModel = true;
            ConnectMarker = marker;
        });
        //T分阶
        kance.setOnClickListener(v -> {
            showInfoWindow(marker, popWindowView, 1);
            jixukance = true;
            jpoints = pointsFist;
            //这里进行适配器和数据的获取然后弹窗
            //TODO 查询 关联的线如果有T分阶线路一个或者十字街线路2个。
            if (jpoints.getIsT().equals("1")) {//表示T分阶
                if (PointsUtils.Companion.isCouldNextT(jpoints, project.getId()) == 1) {
                    com.blankj.utilcode.util.ToastUtils.showShort("T分阶路线最多一个");
                    return;
                }
            } else if (PointsUtils.Companion.isCouldNextSzj(jpoints, project.getId()) == 2) {
                com.blankj.utilcode.util.ToastUtils.showShort("十字接分阶路线最多2个");
                return;
            }
            showMyDialog();
            currentMarker = marker;
            isTfenjieState = 1;
            //修改线对应的关联关系吧？
            creatPolyline(WHETHER_TO_SHOW_GUIDES);
        });
        //继续勘测
        jixuKanceTv.setOnClickListener(v -> {
            showInfoWindow(marker, popWindowView, 1);
            jixukance = true;
            jpoints = pointsFist;
            currentMarker = marker;
            isTfenjieState = 0;
            //修改线对应的关联关系吧？
            creatPolyline(WHETHER_TO_SHOW_GUIDES);
        });
        xiugai.setOnClickListener(v -> {
            showInfoWindow(marker, popWindowView, 1);
            Intent intent = new Intent(context, EquActivity.class);
            intent.putExtra("point", pointsFist);
            intent.putExtra("flag", "1");
            startActivity(intent);
        });
        yidong.setOnClickListener(v -> {
            showInfoWindow(marker, popWindowView, 1);
            jixukance = true;
            jpoints = pointsFist;
            activity_tv_quxiao.setVisibility(View.VISIBLE);
            activity_tv_save.setVisibility(View.VISIBLE);

            iv_center.setBackgroundResource(R.drawable.define_blue);
            mainBtnTerrain.setVisibility(View.GONE);
            mainBtnTower.setVisibility(View.GONE);
            mainBtnFacility.setVisibility(View.GONE);
            switch (pointsFist.getName()) {
                case "通讯线":
                    map_btn_four.setBackgroundResource(R.drawable.dixingdian1);
                    map_btn_four.setVisibility(View.VISIBLE);
                    break;
                case "杆塔":
                    map_btn_four.setBackgroundResource(R.drawable.ganta1);
                    map_btn_four.setVisibility(View.VISIBLE);
                    break;
                default:
                    map_btn_four.setBackgroundResource(R.drawable.shebie1);
                    map_btn_four.setVisibility(View.VISIBLE);
                    break;
            }

            mainBtnFacility.setEnabled(false);//设备
            mainBtnTerrain.setEnabled(false);//底薪点
            mainBtnTower.setEnabled(false);//杆塔

            //点击取消时的操作
            activity_tv_quxiao.setOnClickListener(v1 -> {
                iv_center.setBackgroundResource(R.drawable.define_green);
                map_btn_four.setVisibility(View.GONE);
                activity_tv_quxiao.setVisibility(View.GONE);
                activity_tv_save.setVisibility(View.GONE);
                mainBtnTerrain.setVisibility(View.VISIBLE);
                mainBtnTower.setVisibility(View.VISIBLE);
                mainBtnFacility.setVisibility(View.VISIBLE);
                mainBtnTerrain.setEnabled(true);
                mainBtnTower.setEnabled(true);
                mainBtnFacility.setEnabled(true);
            });

            //点击确定时的操作
            activity_tv_save.setOnClickListener(v12 -> {
                double lat = mMapView.getMapCenter().getLatitude() - pointsFist.getLatitude();
                double lon = mMapView.getMapCenter().getLongitude() - pointsFist.getLongitude();
                if (Distance(mMapView.getMapCenter().getLatitude(), Double.valueOf(mMapView.getMapCenter().getLongitude() + ""), pointsFist.getLatitude(), pointsFist.getLongitude()) < 0.6) {
                    com.blankj.utilcode.util.ToastUtils.showShort("移动距离太近，请重新选择移动位置");
                    return;
                }
                iv_center.setBackgroundResource(R.drawable.define_green);
                map_btn_four.setVisibility(View.GONE);
                activity_tv_quxiao.setVisibility(View.GONE);
                activity_tv_save.setVisibility(View.GONE);
                mainBtnTerrain.setVisibility(View.VISIBLE);
                mainBtnTower.setVisibility(View.VISIBLE);
                mainBtnFacility.setVisibility(View.VISIBLE);//设备
                mainBtnTerrain.setEnabled(true);
                mainBtnTower.setEnabled(true);
                mainBtnFacility.setEnabled(true);
                pointsFist.setLatitude(mMapView.getMapCenter().getLatitude());
                pointsFist.setLongitude(mMapView.getMapCenter().getLongitude());
                getInstances().getDaoSession().getPointDao().update(pointsFist);
                marker.setPosition(new GeoPoint(mMapView.getMapCenter().getLatitude(), mMapView.getMapCenter().getLongitude()));
                List<Line> relateLines = getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.Start_id.eq(pointsFist.getUid()), LineDao.Properties.End_id.eq(pointsFist.getUid())).build().list();
                for (Line l : relateLines) {
                    if (l.getStart_id().equals(pointsFist.getUid())) {
                        l.setLatA(Double.parseDouble(l.getLatA()) + lat + "");
                        l.setLonA(Double.parseDouble(l.getLonA()) + lon + "");
                        BigDecimal bg = new BigDecimal(Distance(Double.valueOf(l.getLatB()), Double.valueOf(l.getLonB()), Double.valueOf(l.getLatA()), Double.valueOf(l.getLonA()))).setScale(0, RoundingMode.UP);
                        l.setLength(bg.intValue() + "");
                        getInstances().getDaoSession().getLineDao().update(l);
                    } else if (l.getEnd_id().equals(pointsFist.getUid())) {
                        l.setLatB(Double.parseDouble(l.getLatB()) + lat + "");
                        l.setLonB(Double.parseDouble(l.getLonB()) + lon + "");
                        BigDecimal bg = new BigDecimal(Distance(Double.valueOf(l.getLatB()), Double.valueOf(l.getLonB()), Double.valueOf(l.getLatA()), Double.valueOf(l.getLonA()))).setScale(0, RoundingMode.UP);
                        l.setLength(bg.intValue() + "");
                        getInstances().getDaoSession().getLineDao().update(l);
                    }
                    //删除辅助线
                    mMapView.getOverlays().remove(mPolyline);
                    //这里删除这个线上面的图层。并且创建一个线图层
                    removeLinePoline(l);
                    //删除档距
                    removeLineMarkerByLine(l);
                    //删除原来的点
                    remove(markerLinkedList, pointsFist.getUid());
                    remove(markerNameLinkedList, pointsFist.getUid());
                    remove(markerEquipList, pointsFist.getUid());
                    addMarker(pointsFist);
                    //画新线
                    drawMyRoute(l);
                }

                createProgressDialog();
                ThreadManager.ThreadPool threadPool = getThreadPool();
                threadPool.execute(mRunnable);
                ToastUtils.showShort("移动成功");
            });
            //画辅助线
            currentMarker = marker;
            creatPolyline(WHETHER_TO_SHOW_GUIDES);
        });

        ///TODO 点的删除
        shanchu.setOnClickListener(v -> {
            showInfoWindow(marker, popWindowView, 1);
            final View views = View.inflate(context, R.layout.activity_map_dialog, null);
            AlertDialog dialog = new AlertDialog.Builder(context).create();
            dialog.setView(views);
            dialog.show();
            Button map_btn_quxiao = views.findViewById(R.id.map_btn_quxiao);
            Button map_btn_queding = views.findViewById(R.id.map_btn_queding);
            map_btn_queding.setOnClickListener(view12 -> {
                dialog.dismiss();
                //TODO 删除点操作。
                getInstances().getDaoSession().getPointDao().delete(pointsFist);
                pointList.remove(pointsFist);
                mMapView.getOverlays().remove(mPolyline);
                List<Equipment> equipmentList = getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(pointsFist.getId())).build().list();
                List<Line> relateLines = getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.Start_id.eq(pointsFist.getUid()), LineDao.Properties.End_id.eq(pointsFist.getUid())).build().list();
                //删除对应的设备、模块、柱上设备等
                if (equipmentList.size() > 0) {
                    for (Equipment equipment : equipmentList) {
                        getInstances().getDaoSession().getEquipmentDao().delete(equipment);
                    }
                }
                //删除线关联点。
                if (relateLines.size() > 0)
                    for (Line line : relateLines) {
                        //TODO 删除线图层
                        for (int i = 0; i < polylineLinkedList.size(); i++) {
                            Polyline nowLine = (polylineLinkedList.get(i));
                            Line line1 = (Line) nowLine.getRelatedObject();
                            if (line1.equals(line)) {
                                //删除集合中的线图层
                                polylineLinkedList.remove(nowLine);
                                //删除地图上点图层
                                mMapView.getOverlays().remove(nowLine);
                            }

                        }
                        //TODO 删除所有点关联线的档距和线的类型
                        //删除地图上线档距和类型
                        for (Marker lenghTypeMark : polylineLengthLinkedList) {
                            if (lenghTypeMark.getId().equals(line.getId().toString())) {
                                mMapView.getOverlays().remove(lenghTypeMark);
                            }
                        }
                        //删除线
                        getInstances().getDaoSession().getLineDao().delete(line);
                    }

                remove(markerLinkedList, pointsFist.getUid());
                //删除点marker图片和marker上下的文字和住上设备
                remove(markerNameLinkedList, pointsFist.getUid());
                //删除柱上设备
                remove(markerEquipList, pointsFist.getUid());
                //跟新当前的currenMarker
                if (markerLinkedList.size() > 0) {
                    currentMarker = markerLinkedList.get(markerLinkedList.size() - 1);
                } else {
                    currentMarker = null;
                }
                mMapView.invalidate();
                createProgressDialog();
                ThreadManager.ThreadPool threadPool = getThreadPool();
                threadPool.execute(mRunnable);
            });
            map_btn_quxiao.setOnClickListener(view1 -> dialog.dismiss());
        });
        quxiao.setOnClickListener(v -> {
            isTfenjieState = 0;
            showInfoWindow(marker, popWindowView, 1);
        });
    }

    ///为分支线路进行创建弹窗和选择
    private void showMyDialog() {
        //获取关联线
        List<Line> allTAbout = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.End_id.eq(jpoints.getUid())).build().list();
        for (int i = 0; i < allTAbout.size(); i++) {
            for (int j = 0; j < allTAbout.size(); j++) {
                if (i != j && allTAbout.get(i).getName().equals(allTAbout.get(j).getName())) {
                    allTAbout.remove(j);
                    j--;
                }
            }
        }
        //这里需要去重复。
        TDialogReAdapter tDialogAdapter = new TDialogReAdapter(context, allTAbout);
        dialogRv.setAdapter(tDialogAdapter);
        dialogRv.setLayoutManager(new LinearLayoutManager(context));
        mapTfzBt.setOnClickListener(v -> {
            tLineId = tDialogAdapter.getTLineId();
            Log.e(TAG, "showMyDialog: " + tLineId);
            dialogFushu.dismiss();
        });
        mapTfzBtCancel.setOnClickListener(v -> {
            dialogFushu.dismiss();
        });
        if (allTAbout.size() > 0) {
            dialogFushu.show();
        }

    }

    public void remove(List<Marker> list, String target) {
        for (int i = list.size() - 1; i >= 0; i--) {
            if (target.equals(list.get(i).getId())) {
                mMapView.getOverlays().remove(list.get(i));
                list.remove(list.get(i));
            }
        }
    }

    /**
     * 创建ProrgressDialog
     */
    private void createProgressDialog() {
        context = this;
        mProgressDialog = new ProgressDialog(context);
        mProgressDialog.setMessage("加载数据中,请稍等...");
        mProgressDialog.show();
    }

    /**
     * 关闭之前所有的marker上的弹窗menu并且显示点击的当前的marker弹窗
     * 对Marker弹窗的操作
     *
     * @param marker
     * @param markerWindow
     * @param flag         1为新增，2为删除
     */
    private void showInfoWindow(Marker marker, MarkerWindow markerWindow, int flag) {
        //关闭之前所有的marker上的弹窗menu
        for (Marker closeMarker : markerLinkedList) {
            closeMarker.closeInfoWindow();
        }
        if (flag == 0) {
            marker.setInfoWindow(markerWindow);
            marker.showInfoWindow();
        } else {
            marker.closeInfoWindow();
        }
        /*ViewGroup.LayoutParams lp= map_tv_xiahu.getLayoutParams();
        lp.width=200;
        lp.height=map_tv_xiahu.getHeight();
        map_tv_xiahu.setLayoutParams(lp);*/
    }

    //创建或更新辅助线
    @SuppressLint({"SetTextI18n", "DefaultLocale"})
    private void creatPolyline(Boolean isOpenOrCloses) {
        List<GeoPoint> geoPointListCenter = new ArrayList<>();
        if (pointList.size() > 0) {
            mainTvLength.setVisibility(View.VISIBLE);
            geoPointListCenter.clear();
            if (currentMarker == null) {
                return;
            }
            if (currentMarker.getId() != null) {
                String pointId = currentMarker.getId();
                Point point = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(pointId)).unique();
                geoPointListCenter.add(new GeoPoint(point.getLatitude(), point.getLongitude()));
            } else {
                geoPointListCenter.add(new GeoPoint(pointList.get(pointList.size() - 1).getLatitude(), pointList.get(pointList.size() - 1).getLongitude()));
            }
            mapCenter = mMapView.getMapCenter();
            point = new GeoPoint(mapCenter.getLatitude(), mapCenter.getLongitude());
            geoPointListCenter.add(point);
            mMapView.getOverlays().remove(mPolyline);
            //mainTvLength.setText(String.format("%.2f", MapUtils.distance(mapCenter.getLatitude(), mapCenter.getLongitude(), pointList.get(pointList.size() - 1).getLatitude(), pointList.get(pointList.size() - 1).getLongitude())) + "米");
            mPolyline = new Polyline();
            mPolyline.setPoints(geoPointListCenter);
            mPolyline.setColor(Color.argb(160, 99, 189, 148));
            mPolyline.setWidth(6);
            mPolyline.setGeodesic(false);
            mPolyline.getPaint().setPathEffect(new DashPathEffect(new float[]{22, 22}, 22));
            mMapView.getOverlays().add(mPolyline);
        } else {
            mainTvLength.setVisibility(View.GONE);
            mMapView.getOverlays().remove(mPolyline);
        }

    }

    private void ConnectTowEquip(Marker connectMarker, Marker marker) {
        Point ptA = (Point) connectMarker.getRelatedObject();
        Point ptB = (Point) marker.getRelatedObject();
        //如果是同一路线就不能连接其他都才可以连接
        List<Point> resultPoints = getAllNodeBettwenSE(ptA, ptB);
        if (resultPoints.size() > 1) {
            com.blankj.utilcode.util.ToastUtils.showShort("已经在同一路线。不能连接");
            return;
        }
        List<Line> lineFromptA2PtB = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(ptA.getUid()), LineDao.Properties.End_id.eq(ptB.getUid())).build().list();
        List<Line> lineFromptB2PtA = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(ptB.getUid()), LineDao.Properties.End_id.eq(ptA.getUid())).build().list();

        if (lineFromptA2PtB.size() == 0 && lineFromptB2PtA.size() == 0) {
            if (ptB.getName().equals("地形点") && !ptB.getEquipType_name().contains("电缆拐点") && !ptB.getEquipType_name().equals("连接点")) {
                com.blankj.utilcode.util.ToastUtils.showShort("地形点不允许连线");
                return;
            }
            final View views = View.inflate(context, R.layout.activity_map_dialog, null);
            AlertDialog dialog = new AlertDialog.Builder(context).create();
            TextView map_tv_title = views.findViewById(R.id.map_tv_title);
            TextView map_tv_content = views.findViewById(R.id.map_tv_content);
            Button map_btn_quxiao = views.findViewById(R.id.map_btn_quxiao);
            Button map_btn_queding = views.findViewById(R.id.map_btn_queding);
            map_tv_title.setText("连接");
            map_tv_content.setText("是否连接两点？");
            dialog.setView(views);
            dialog.show();
            map_btn_queding.setOnClickListener(view12 -> {
                dialog.dismiss();
                /**
                 * 如果上一个点是T分阶那么我们
                 * //点A的经度  是否T分支 如果是  为1 ,主干点 "" 十字接 2
                 */
                List<Line> gulianLine = new ArrayList<>(LineUtils.getInstance().getGuanLianLine(ptA));
                if (gulianLine.size() > 0) {
                    for (Line l : gulianLine) {
                        Line line = LineUtils.getInstance().getConneLine(l, project, ptA, ptB);
                        drawMyRoute(line);
                        ConnectEquipModel = false;
                        ToastUtils.showShort("连接成功");
                    }
                } else {
                    Line line = LineUtils.getInstance().getConneLineNew(project, ptA, ptB);
                    drawMyRoute(line);
                    ConnectEquipModel = false;
                    ToastUtils.showShort("连接成功");
                }
            });
            map_btn_quxiao.setOnClickListener(view1 -> {
                ConnectEquipModel = false;
                dialog.dismiss();
            });
        } else {
            ToastUtils.showShort("两者之间已连接");
        }
    }


    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Toast.makeText(this, "已拒绝权限定位并不再询问", Toast.LENGTH_SHORT).show();
        new AppSettingsDialog.Builder(this)
                .setRationale("此功能需要定位权限，否则无法正常使用，是否打开设置")
                .setPositiveButton("是")
                .setNegativeButton("否")
                .build()
                .show();
        finish();
    }

    /**
     * 进来有点的话移动到当前位置
     *
     * @param geoPoint 所有点的中点
     */
    @Override
    public void toPointsLocation(GeoPoint geoPoint) {
        //动画平移到当前位置
        mapController.animateTo(geoPoint, mMapView.getZoomLevelDouble(), 200L);
    }

    /**
     * 初始化获得项目的有关信息
     *
     * @param project              当前项目信息
     * @param pointList            点集合
     * @param lineList             线集合
     * @param withTheLeverLineList 同杆并架集合
     */
    @Override
    public void initPointAndLine(Project project, List<Point> pointList, List<Line> lineList, List<Line> withTheLeverLineList) {
        this.project = project;
        this.pointList = pointList;
        this.parallelPoleList = withTheLeverLineList;
        mainTitleBar.setTitle(project.getName());
        if (lineList.size() > 0) {
            for (int i = 0; i < lineList.size(); i++) {
                if (lineList.get(i).getType().contains("架空")) {
                    lineList.get(i).setPath("");
                }
                App.getInstances().getDaoSession().getLineDao().update(lineList.get(i));
                drawMyRoute(lineList.get(i));
            }
        }
        if (pointList.size() > 0) {
            for (int i = 0; i < pointList.size(); i++) {
                addMarker(pointList.get(i));
                latList.add(pointList.get(i).getLatitude());
                longList.add(pointList.get(i).getLongitude());
            }
            //将地图中心点移动到所有点的中心
            //getPresenter().toPointsLocation(latList, longList);
        } else {
            //找不到地图加载完成监听，无法自动跳转到当前位置，手动跳转
            //new Handler().postDelayed(this::location, 1000);
            currentMarker = null;
        }
        if (!parallelPoleList.isEmpty())//如果同杆并架不为空的情况下加载同杆并架
            for (int i = 0; i < parallelPoleList.size(); i++) {
                drawMyRoute(parallelPoleList.get(i));
            }
        //drawParallelWithBar();
    }

    /**
     * SingleClick 通过aop实现防止按钮重复点击
     *
     * @param v /
     */
    @Override
    //@SingleClick(value = 500)
    public void onClick(View v) {
        String MAIN_ADD_FACILITY = "设备";
        switch (v.getId()) {
            //新增杆塔
            //屏幕下方杆塔的按钮
            case R.id.mainBtnTower: {
//                ConnectEquipModel = false;
//                if (maxDistance <= 1000) {//不能超过公里。
//                    IGeoPoint mapCenter = mMapView.getMapCenter();
//                    getPresenter().saveMarkerAndLine(new AddMarkerAndLine(context, project, isTfenjieState, WHETHER_TO_SHOW_GUIDES, high, address, currentMarker, mapCenter, EquipmentCateGoryEmm.NEWTOWER));
//                } else {
//                    ToastUtils.showShort(getString(R.string.map_distance_max));
//                }
            }
            break;
            //定位到当前位置
            case R.id.mainIbLocation:
                location();
                break;
            //新增地形点
            case R.id.mainBtnTerrain: {
                ConnectEquipModel = false;
                if (maxDistance <= 1000) {//不能超过公里。
                    IGeoPoint mapCenter = mMapView.getMapCenter();
                    getPresenter().saveMarkerAndLine(new AddMarkerAndLine(context, project, isTfenjieState, WHETHER_TO_SHOW_GUIDES, high, address, currentMarker, mapCenter, EquipmentCateGoryEmm.NEWGONEJINE));
                } else {
                    ToastUtils.showShort(getString(R.string.map_distance_max));
                }
//                ConnectEquipModel = false;
//                if (maxDistance <= 1000) {//不能超过公里。
//                    IGeoPoint mapCenter = mMapView.getMapCenter();
//                    getPresenter().saveMarkerAndLineTopographic(new AddMarkerAndLinePol(context, project, false, high, address, currentMarker, mapCenter, EquipmentCateGoryEmm.NEWTOWER, jixukance, jpoints));
//                } else {
//                    ToastUtils.showShort(getString(R.string.map_distance_max));
//                }
            }
            break;
            //新增共井
            case R.id.main_gonjin: {
                ConnectEquipModel = false;
                if (maxDistance <= 1000) {//不能超过公里。
                    IGeoPoint mapCenter = mMapView.getMapCenter();
                    getPresenter().saveMarkerAndLine(new AddMarkerAndLine(context, project, isTfenjieState, WHETHER_TO_SHOW_GUIDES, high, address, currentMarker, mapCenter, EquipmentCateGoryEmm.NEWGONEJINE));
                } else {
                    ToastUtils.showShort(getString(R.string.map_distance_max));
                }
            }
            break;
            //新增设备
            case R.id.mainBtnFacility: {
                ConnectEquipModel = false;
                if (maxDistance <= 1000) {//不能超过公里。
                    IGeoPoint mapCenter = mMapView.getMapCenter();
                    getPresenter().saveMarkerAndLine(new AddMarkerAndLine(context, project, isTfenjieState, WHETHER_TO_SHOW_GUIDES, high, address, currentMarker, mapCenter, EquipmentCateGoryEmm.NEWEQUIPMENT));
                } else {
                    ToastUtils.showShort(getString(R.string.map_distance_max));
                }
            }
            break;
            case R.id.map_btn_model:
                //拖动模式
                if (App.getInstances().btn_model) {
                    App.getInstances().btn_model = false;
                    mapState.setBackgroundResource(R.drawable.tuodongmoshi);
                } else {
                    //卫星模式
                    App.getInstances().btn_model = true;
                    mapState.setBackgroundResource(R.drawable.weixingmoshi);
                }
                break;
            case R.id.map_viewAll://显示所有的点在地图中间可视。
                //将地图中心点移动到所有点的中心
                if (!latList.isEmpty() && !longList.isEmpty()) {
                    getPresenter().toPointsLocation(latList, longList);
                }
                break;
            case R.id.map_btn_name://显示mar名称和住上设备等等图层。
                //编号显示
                WHETHER_TO_DISPLAY_THE_NUMBER = !WHETHER_TO_DISPLAY_THE_NUMBER;
                for (int i = 0; i < markerNameLinkedList.size(); i++) {
                    markerNameLinkedList.get(i).setVisible(WHETHER_TO_DISPLAY_THE_NUMBER);
                }
                for (int i = 0; i < markerEquipList.size(); i++) {
                    markerEquipList.get(i).setVisible(WHETHER_TO_DISPLAY_THE_NUMBER);
                }
                break;
            case R.id.map_btn_length:
                //档距显示
                WHETHER_TO_DISPLAY_THE_PITCH = !WHETHER_TO_DISPLAY_THE_PITCH;
                for (int i = 0; i < polylineLengthLinkedList.size(); i++) {
                    polylineLengthLinkedList.get(i).setVisible(WHETHER_TO_DISPLAY_THE_PITCH);
                }
                break;
            case R.id.map_open_line://辅助线
                if (mPolyline != null) {
                    mPolyline.setVisible(!mPolyline.isVisible());
                    WHETHER_TO_SHOW_GUIDES = !WHETHER_TO_SHOW_GUIDES;
                } else {
                    WHETHER_TO_SHOW_GUIDES = !WHETHER_TO_SHOW_GUIDES;
                    creatPolyline(WHETHER_TO_SHOW_GUIDES);
                }
                break;
            case R.id.two_local:
                getInstances().isXinJian = false;
                mMapView.getOverlays().clear();
                two_local.setTextColor(Color.rgb(255, 255, 255));
                two_online.setTextColor(Color.rgb(51, 51, 51));
                two_local.setBackgroundResource(R.drawable.btn_city_up);
                two_online.setBackgroundResource(R.drawable.btn_down_white);
                initData();
                break;
            case R.id.two_online:
                getInstances().isXinJian = true;
                mMapView.getOverlays().clear();
                two_online.setTextColor(Color.rgb(255, 255, 255));
                two_local.setTextColor(Color.rgb(51, 51, 51));
                two_local.setBackgroundResource(R.drawable.btn_city_white);
                two_online.setBackgroundResource(R.drawable.btn_down_up);
                initData();
                break;
        }
    }

    /**
     * -----------------------------------------------------start----------------------画点和住上设备操作-------------------------------------------------------
     * wangfei
     * view层绘制刚刚新建的Marker
     *
     * @param point
     * @param jixukance
     */
    @Override
    public void drawMarker(Point point, Line line, boolean jixukance) {
        isTfenjieState = 0;
        //添加marker
        pointList.add(point);
        //TODO 线 去添加线 和 档距
        jixukance = false;
        addMarker(point);
        Intent intent = new Intent(context, EquActivity.class);
        intent.putExtra("point", point);
        intent.putExtra("line", line);
        intent.putExtra("name", "杆塔");
        intent.putExtra("flag", "0");
        intent.putExtra("tLineId", tLineId);
        startActivity(intent);
    }

    /**
     * 添加Marker
     */
    private void addMarker(Point p) {
        latList.add(p.getLatitude());
        longList.add(p.getLongitude());
        //获取点的Marker
        Marker poiMarker = PointsUtils.Companion.getInstance().getPointMarker(p, this, mMapView);
        setMarkerInfoWindow(poiMarker);
        markerLinkedList.add(poiMarker);
        /**
         *这个是杆塔/底薪点/设备的mark名称
         */
        Marker m = PointsUtils.Companion.getInstance().getPointMarkerNameMarker(mMapView, p, WHETHER_TO_DISPLAY_THE_NUMBER);
        /*markerNameLinkedList.add(m);
        mMapView.getOverlays().add(m);*/
        /**
         * 刷新当前的marker
         */
        //currentMarker = m;
        /**
         * 点聚合
         */
        mMapView.getOverlays().add(poiMarker);
        Log.e("p.toStingwf=", p.toString1());
        if (p.getDefaultLineType() != null && p.getMark() != null && !p.getMark().equals("") && !p.getDefaultLineType().equals("0")) {
            Log.e("pp.toStingwf=", p.toString1());
            currentMarker = m;
        }
        creatPolyline(WHETHER_TO_SHOW_GUIDES);
        //这里去添加住上设备
        viewMarks(m);
    }

    /**
     * 柱上设备。
     *
     * @param marker /
     */
    private void viewMarks(Marker marker) {
        Marker lineTypeMarker = PointsUtils.Companion.getInstance().getPointEquipmentMarks(marker, this, mMapView, WHETHER_TO_DISPLAY_THE_NUMBER);
        markerEquipList.add(lineTypeMarker);
        mMapView.getOverlays().add(lineTypeMarker);
    }

    /***
     * 设置Marker点的点击事件
     * @param marker marker
     */
    private void setMarkerInfoWindow(Marker marker) {
        /**
         * 如果返回true就消费掉当前事件。
         * 如果返回false会调用map上所有的marker所以onMarkerClick内部会走完所有的事件。
         */
        marker.setOnMarkerClickListener((poiMarker, mapView) -> {
            String mMarkerId = marker.getId();
            if (mMarkerId == null || mMarkerId.isEmpty()) {
                return false;
            }
            //同杆并架
            if (CHOOSE_POINT) {
                createCircuit(marker);
                //拉直所在的直线
            } else if (CHOOSE_PINTZX) {
                createCircuitZhiLine(marker);
            } else {
                // setMarkerInfoWindowClick(marker, poiMarker);
                clickMarker(marker);
            }
            //返回
            return true;
        });
    }

    /**
     * 同杆并架存储线
     *
     * @param marker /
     */
    private void createCircuit(Marker marker) {
        Point pointsFist = (Point) marker.getRelatedObject();
        if (pointsFist.getName().contains("杆塔")) {
            if (pointsFist.getUid().equals(latLngList.getUid())) {
                ToastUtils.showShort("不能选择已选杆塔");
            } else {
                List<Line> lineLista = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.ProjectId.eq(project.getId()), LineDao.Properties.Start_id.eq(pointsFist.getUid()), LineDao.Properties.End_id.eq(latLngList.getUid())).build().list();
                List<Line> lineListb = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.ProjectId.eq(project.getId()), LineDao.Properties.Start_id.eq(latLngList.getUid()), LineDao.Properties.End_id.eq(pointsFist.getUid())).build().list();
                CHOOSE_POINT = false;
                lineLista.addAll(lineListb);
                int lineNum = lineLista.size();
                if (lineNum < 2) {
                    final View views = View.inflate(context, R.layout.activity_map_dialog, null);
                    AlertDialog dialog = new AlertDialog.Builder(context).create();
                    TextView map_tv_title = views.findViewById(R.id.map_tv_title);
                    TextView map_tv_content = views.findViewById(R.id.map_tv_content);
                    Button map_btn_quxiao = views.findViewById(R.id.map_btn_quxiao);
                    Button map_btn_queding = views.findViewById(R.id.map_btn_queding);
                    map_tv_title.setText("同杆并架");
                    map_tv_content.setText("是否要同杆并架？");
                    dialog.setView(views);
                    dialog.show();
                    double degree = bearing(pointsFist.getLatitude(), pointsFist.getLongitude(), latLngList.getLatitude(), latLngList.getLongitude());
                    double degrees = degree - 180;
                    map_btn_queding.setOnClickListener(view12 -> {
                        dialog.dismiss();
                        CHOOSE_POINT = false;
                        List<Point> resultPoints = getAllNodeBettwenSE(latLngList, pointsFist);
                        if (lineNum == 0) {
                            //知道了 第一个点和最后一个点   pointFist   latLngList
                            //知道了 第一个点和最后一个点   pointFist   latLngList
                            for (int i = 0; i < resultPoints.size() - 1; i++) {
                                Point onePoints = resultPoints.get(i);
                                Point twoPoints = resultPoints.get(i + 1);
                                List<Line> lineListaa = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(project.getId()), LineDao.Properties.Start_id.eq(onePoints.getUid()), LineDao.Properties.End_id.eq(twoPoints.getUid())).build().list();
                                List<Line> lineListbb = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(project.getId()), LineDao.Properties.Start_id.eq(twoPoints.getUid()), LineDao.Properties.End_id.eq(onePoints.getUid())).build().list();
                                lineListaa.addAll(lineListbb);
                                int lineNumab = lineListaa.size();
                                if (lineNumab < 2) {
                                    addTongGanNewLine(onePoints, twoPoints, 0.0, degrees, 0);
                                }
                            }

                        } else if (lineNum == 1) {
                            for (int i = 0; i < resultPoints.size() - 1; i++) {
                                com.zj.osm.entity.greendao.Point onePoints = resultPoints.get(i);
                                com.zj.osm.entity.greendao.Point twoPoints = resultPoints.get(i + 1);
                                List<Line> lineListaa = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.ProjectId.eq(project.getId()), LineDao.Properties.Start_id.eq(onePoints.getUid()), LineDao.Properties.End_id.eq(twoPoints.getUid())).build().list();
                                List<Line> lineListbb = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.ProjectId.eq(project.getId()), LineDao.Properties.Start_id.eq(twoPoints.getUid()), LineDao.Properties.End_id.eq(onePoints.getUid())).build().list();
                                lineListaa.addAll(lineListbb);
                                int lineNumab = lineListaa.size();
                                if (lineNumab < 2) {
                                    addTongGanNewLine(onePoints, twoPoints, 0.000025, degrees, 10);
                                }
                            }
                        } else {
                            for (int i = 0; i < resultPoints.size() - 1; i++) {
                                com.zj.osm.entity.greendao.Point onePoints = resultPoints.get(i);
                                com.zj.osm.entity.greendao.Point twoPoints = resultPoints.get(i + 1);
                                android.graphics.Point onePoint = mMapView.getProjection().toPixels(new GeoPoint(onePoints.getLatitude(), onePoints.getLongitude()), null);
                                android.graphics.Point twoPoint = mMapView.getProjection().toPixels(new GeoPoint(twoPoints.getLatitude(), twoPoints.getLongitude()), null);
                                List<android.graphics.Point> onePointss = LineUtils.getInstance().getTongGanBingjia(onePoint, twoPoint, (int) degrees, "0");
                                LatLng onetLat = new LatLng(mMapView.getProjection().fromPixels(onePointss.get(0).x, onePointss.get(0).y).getLatitude(), mMapView.getProjection().fromPixels(onePointss.get(0).x, onePointss.get(0).y).getLongitude());
                                LatLng twoLat = new LatLng(mMapView.getProjection().fromPixels(onePointss.get(1).x, onePointss.get(1).y).getLatitude(), mMapView.getProjection().fromPixels(onePointss.get(1).x, onePointss.get(1).y).getLongitude());
                                onePoints.setLatitude(onetLat.latitude);
                                onePoints.setLongitude(onetLat.longitude);
                                twoPoints.setLatitude(twoLat.latitude);
                                twoPoints.setLongitude(twoLat.longitude);
                                List<Line> lineListaa = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.ProjectId.eq(project.getId()), LineDao.Properties.Start_id.eq(onePoints.getUid()), LineDao.Properties.End_id.eq(twoPoints.getUid())).build().list();
                                List<Line> lineListbb = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.ProjectId.eq(project.getId()), LineDao.Properties.Start_id.eq(twoPoints.getUid()), LineDao.Properties.End_id.eq(onePoints.getUid())).build().list();
                                lineListaa.addAll(lineListbb);
                                int lineNumab = lineListaa.size();
                                if (lineNumab < 2) {
                                    addTongGanNewLine(onePoints, twoPoints, -0.000025, degrees, -10);
                                }

                            }
                        }

                    });
                    map_btn_quxiao.setOnClickListener(view1 -> {
                        CHOOSE_POINT = false;
                        dialog.dismiss();
                    });
                } else {
                    com.blankj.utilcode.util.ToastUtils.showShort("两点之间绘制线最多2条线路");
                }
            }
        } else {
            com.blankj.utilcode.util.ToastUtils.showShort("请选择杆塔");
        }

    }

    /**
     * -----------------------------------------------------End----------------------画点和住上设备操作-------------------------------------------------------
     */
    public void drawCircleToQg(List<GeoPoint> geoPoints) {
        Polyline polyline = new Polyline();
        polyline.setWidth(10);
        polyline.setColor(Color.parseColor("#DA382F"));
        polyline.setPoints(geoPoints);//设置线到开始点和结束点
        mMapView.getOverlays().add(polyline);
    }

    /**
     * -----------------------------------------------------Start----------------------画线路-------------------------------------------------------
     *
     * @param line 添加绘制线路
     */
    @SuppressLint("SetTextI18n")
    @Override
    public void drawMyRoute(Line line) {
        Log.e("line======", line.toString());
        Polyline ooPolyline = LineUtils.getInstance().getPolyLine(line);
        ooPolyline.setRelatedObject(line);
        LatLng lng1 = new LatLng(Double.valueOf(line.getLatA()), Double.valueOf(line.getLonA()));
        LatLng lng2 = new LatLng(Double.valueOf(line.getLatB()), Double.valueOf(line.getLonB()));
        //添加到线路图层里面
        polylineLinkedList.add(ooPolyline);
        //添加线到里面
        mMapView.getOverlays().add(ooPolyline);
        if (WHETHER_TO_SHOW_GUIDES) {
            //画档距
            LatLng latLng = new LatLng((lng2.latitude + lng1.latitude) / 2, (lng1.longitude + lng2.longitude) / 2);
            GeoPoint mGeoPoint = new GeoPoint(latLng.latitude, latLng.longitude);
            if (line.getTypes() != null) {
                //绘制线路上面的类型Mark
                Marker lineTypeMarker = LineUtils.getInstance().getLineTypeMarker(line, mMapView, mGeoPoint, WHETHER_TO_DISPLAY_THE_PITCH, lng1, lng2);
                polylineLengthLinkedList.add(lineTypeMarker);
                mMapView.getOverlays().add(lineTypeMarker);
                //setLineMarkInfoWindow(lineTypeMarker, 1);
            }
            if (line.getLength() != null) {
                Marker lineDangjuMarker = LineUtils.getInstance().getLineDistanceMarker(line, mMapView, mGeoPoint, WHETHER_TO_DISPLAY_THE_PITCH, lng1, lng2);
                polylineLengthLinkedList.add(lineDangjuMarker);
                mMapView.getOverlays().add(lineDangjuMarker);
                //setLineMarkInfoWindow(lineDangjuMarker, 0);
            }

        }
        //添加弹窗线到
        setLineInfoWindow(ooPolyline);
    }

    /**
     * 设置线的点击事件
     *
     * @param line 线
     */
    private void setLineInfoWindow(Polyline line) {
        line.setOnClickListener((polyline, mapView, eventPos) -> {
            Line linMark = (Line) polyline.getRelatedObject();
            GeoPoint pointGeo = new GeoPoint((Double.parseDouble(linMark.getLatA()) + Double.parseDouble(linMark.getLatB())) / 2, (Double.parseDouble(linMark.getLonA()) + Double.parseDouble(linMark.getLonB())) / 2);
            Log.e("点击了==", "我去？？");
            if (overlay != null && overlay.isInfoWindowOpen())
                overlay.closeInfoWindow();
            overlay = polyline;
            LineInfoWindow lineInfoWindow = new LineInfoWindow(R.layout.layout_line_dialog, mMapView);
            polyline.setInfoWindow(lineInfoWindow);
            polyline.addPoint(pointGeo);
            polyline.getInfoWindow().open(null, pointGeo, 0, 0);
            Line clickLine = (Line) polyline.getRelatedObject();
            //获取view
            TextView xiugai = polyline.getInfoWindow().getView().findViewById(R.id.map_tv_xiugai);
            TextView yidong = polyline.getInfoWindow().getView().findViewById(R.id.map_tv_yidong);
            TextView shanchu = polyline.getInfoWindow().getView().findViewById(R.id.map_tv_shanchu);
            TextView quxiao = polyline.getInfoWindow().getView().findViewById(R.id.map_tv_quxiao);
            yidong.setText("插入");
            //修改
            xiugai.setOnClickListener(v -> {
                Intent intent = new Intent(context, LineActivity.class);
                intent.putExtra("line", (Line) line.getRelatedObject());
                startActivity(intent);
                polyline.getInfoWindow().close();
                //showInfoWindow(view, getLatLng(polyline.getPoints()), 1);
            });
            //插入杆塔
            yidong.setOnClickListener(v -> {
                Intent intent = new Intent(context, DistanceActivity.class);
                intent.putExtra("line", (Line) line.getRelatedObject());
                startActivity(intent);
                polyline.getInfoWindow().close();
                //showInfoWindow(view, getLatLng(polyline.getPoints()), 1);
            });
            //TODO 线的删除
            shanchu.setOnClickListener(v -> {
                polyline.getInfoWindow().close();
                //showInfoWindow(view, getLatLng(polyline.getPoints()), 1);
                final View views = View.inflate(context, R.layout.activity_map_dialog, null);
                AlertDialog dialog = new AlertDialog.Builder(context).create();
                dialog.setView(views);
                dialog.show();
                Button map_btn_quxiao = views.findViewById(R.id.map_btn_quxiao);
                Button map_btn_queding = views.findViewById(R.id.map_btn_queding);
                map_btn_queding.setOnClickListener(view12 -> {
                    dialog.dismiss();
                    removeLineMarker(line);
                    getInstances().getDaoSession().getLineDao().delete((Line) line.getRelatedObject());
                });
                map_btn_quxiao.setOnClickListener(view1 -> dialog.dismiss());

            });

            quxiao.setOnClickListener(v -> polyline.getInfoWindow().close());
            return true;
        });

    }

    private void removeLineMarker(Polyline line) {
        mMapView.getOverlays().remove(line);
        Line mline = (Line) line.getRelatedObject();
        //删除地图上线档距和类型
        remove(polylineLengthLinkedList, mline.getId().toString());
    }

    private void removeLineMarkerByLine(Line line) {
        for (int i = 0; i < polylineLengthLinkedList.size(); i++) {
            Marker marker = polylineLengthLinkedList.get(i);
            Line line1 = (Line) marker.getRelatedObject();
            if (line1.getCid().equals(line.getCid())) {
                mMapView.getOverlays().remove(line);
            }
        }
    }
    /**
     * -----------------------------------------------------End----------------------画线路-------------------------------------------------------
     *
     */
    /**
     * 保存点
     *
     * @param icon 类型 （图片）
     */
    @SuppressLint("DefaultLocale")
    private void saveMarker(String icon) {
        IGeoPoint mapCenter = mMapView.getMapCenter();
        //向数据库中插入数据
        getPresenter().addPointAndLine(project.getId(), icon, mapCenter, pointList);
    }

    /**
     * 设置地图源 有网路情况下直接使用网络，没网情况下加载离线地图
     */
    private void setMapSources() {
        String defaultMapFlag = SPUtils.getInstance().getString("DEFAULT_MAP_FLAG");
        if (defaultMapFlag.equals("ONLINE_MAP")) {
            String mapSource = SPUtils.getInstance().getString(MAP_TILE_SOURCE);
            if (!TextUtils.isEmpty(mapSource)) {
                Log.e("resource=", mapSource);
                mMapView.setTileSource(Objects.requireNonNull(GoogleTileSource.getOnlineTileSourceBaseByName("tianDiTuImgTileSource")));

                //mMapView.setTileSource(Objects.requireNonNull(GoogleTileSource.GoogleHybrid));
            }
        } else {
            //ToastUtils.showShort("当前无网络，请选择离线地图包");
            if (mMapView.getOverlays().size() <= 0) {
                //GoogleTileSource.mapViewOtherData("/osmdroid/china.sqlite", new SoftReference<>(this), mMapView);
                File file = GoogleTileSource.mapViewOtherData("/osmdroid/" + defaultMapFlag);
                OfflineTileProvider tileProvider = null;
                try {
                    tileProvider = new OfflineTileProvider(new SimpleRegisterReceiver(this), new File[]{file});
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mMapView.setTileProvider(tileProvider);
            }
        }
    }

    /**
     * 定位到当前位置
     */
    private void location() {
        //判空，不然会报错
        //TODO
        //if (mLocationOverlay != null && mLocationOverlay.mMyLocationProvider != null && mLocationOverlay.mMyLocationProvider.getLastKnownLocation() != null) {
        if (useLocation != null) {
            //地球坐标系=>火星坐标系
            //double[] wgs2GCJ = GPSUtils.wgs2GCJ(mLocationOverlay.mMyLocationProvider.getLastKnownLocation().getLatitude(), mLocationOverlay.mMyLocationProvider.getLastKnownLocation().getLongitude());
            double latitude = useLocation.getLatitude();
            double longitude = useLocation.getLongitude();
            Log.e("dingwei中心==", "latitude" + latitude + ":" + "longitude" + longitude);
            if (latitude > 0 && longitude > 0) {
                mapController = mMapView.getController();
                mapController.setZoom(18.0);
                GeoPoint startPoint = new GeoPoint(latitude, longitude);
                //动画平移到当前位置
                mapController.animateTo(startPoint, mMapView.getZoomLevelDouble(), 100L);
            }
        } else {
            ToastUtils.showShort("没有获取到当前位置，请稍后重试");
        }
    }


    /**
     * 权限问题
     */
    private void showContacts() {
        EasyPermissions.requestPermissions(this, "申请权限", 0,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        initMap();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mMinimapOverlay != null) {
            mMinimapOverlay.onPause();

        }
        mMapView.onPause();  //needed for compass, my location overlays, v6.0.0 and up
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (drawable != null) {
            drawable = null;
        }
        if (mMinimapOverlay != null && mMapView != null) {
            mMinimapOverlay.onDetach(mMapView);
        }
        ChinaLocation.getInstance().close();
    }

    DisplayMetrics getScrreen() {
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(metric);
        return metric;
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onLocationChanged(Location location) {
       /* //TODO
        //实时获取位置用户的.
        useLocation = location;
        high = location.getAltitude();
        //判断GPS定位如果关闭,如果再次GPS获取到定位那么就再次让其初始化 用来获取地图中心点。
        *//*if (mLocationOverlay == null || mLocationOverlay.mMyLocationProvider == null || mLocationOverlay.mMyLocationProvider.getLastKnownLocation() == null) {
            this.mLocationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(this), mMapView);

        }*//*
        //判空，不然会报错
        //地球坐标系=>火星坐标系
        if (App.getInstances().btn_model) {//只有卫星模式才可以进行。
            double[] wgs2GCJ = GPSUtils.wgs2GCJ(location.getLatitude(), location.getLongitude());
            double latitude = wgs2GCJ[0];
            double longitude = wgs2GCJ[1];
            Log.e("dingwei==", "latitude" + latitude + ":" + "longitude" + longitude);
            if (latitude > 0 && longitude > 0) {
                mapController = mMapView.getController();
                GeoPoint enen = new GeoPoint(latitude, longitude);
               *//* if(this.is) {
                    Marker poiMarker = new Marker(mMapView);
                    poiMarker.setPosition(enen);
                    Drawable drawable = getResources().getDrawable(R.drawable.yuandian);
                    poiMarker.setIcon(drawable);
                    mMapView.getOverlays().add(poiMarker);
                }*//*
                //动画平移到当前位置
                mapController.animateTo(enen, mMapView.getZoomLevelDouble(), 100L);
            }
        }*/

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.e("status==", status + "");
        ToastUtils.showShort("status");
    }

    @Override
    public void onProviderEnabled(String provider) {
        ToastUtils.showShort("GPS已打开");
    }

    @Override
    public void onProviderDisabled(String provider) {
        ToastUtils.showShort("GPS已关闭");
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
    }

    /**
     * 获取UUID
     *
     * @return uuid
     */
    private String getUUID() {
        return UUID.randomUUID() + "";
    }

    @Override
    public void continuingSurvey(Point point) {
        pointList.remove(point);
        pointList.add(point);
    }

    /**
     * @param pointsFist
     * @param latLngList
     */
    private List<Point> getAllNodeBettwenSE(Point pointsFist, Point latLngList) {
        ThreeUtils utilsNode = new ThreeUtils();
        //获取根节点 下面的所有线
        lstTempPoints.clear();
        lstTempPoints.add(pointsFist);
        PointNode rootPointNode = new PointNode();
        rootPointNode.setNode(pointsFist);
        rootPointNode.setChilderNodeList(getChildenNodeList(rootPointNode));
        String path = "";
        paths.clear();
        FindAllPaths(rootPointNode, latLngList.getUid(), path);
        return getTonganBinjia(paths.toString().replace("[", "").replace("]", ""));
    }

    /**
     * 获取所有的同杆并架的点。
     *
     * @param pathss
     */
    private List<Point> getTonganBinjia(String pathss) {
        List<Point> tongganAllpoints = new ArrayList<>();
        String[] strin = pathss.split("\\|");
        for (int i = 0; i < strin.length; i++) {
            Point itemPoints = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(project.getId()), PointDao.Properties.Uid.eq(strin[i])).unique();
            tongganAllpoints.add(itemPoints);
        }
        return tongganAllpoints;

    }

    //递归取子节点集合
    private List<PointNode> getChildenNodeList(PointNode pointNode) {
        List<PointNode> lstPointNode = new ArrayList<>();
        List<Point> lstPoints = getRelationPoints(pointNode.getNode());

        if (lstPoints.size() == 1 && lstTempPoints.contains(lstPoints.get(0)))
            return null;
        for (Point p : lstPoints) {
            if (!lstTempPoints.contains(p)) {
                lstTempPoints.add(p);
                PointNode newPointNode = new PointNode();
                newPointNode.setNode(p);
                List<PointNode> relatoin = getChildenNodeList(newPointNode);
                newPointNode.setChilderNodeList(relatoin);
                lstPointNode.add(newPointNode);
            }
        }
        return lstPointNode;
    }

    //根据连接关系取与自己连接所有节点，不包括自己
    private List<Point> getRelationPoints(Point points) {
        List<Line> relationLines = App.getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.Start_id.eq(points.getUid()), LineDao.Properties.End_id.eq(points.getUid())).list();
        LinkedList<String> PointsUids = new LinkedList<>();
        for (Line l : relationLines) {

            if (!PointsUids.contains(l.getStart_id()) && !l.getStart_id().equals(points.getUid()))
                PointsUids.add(l.getStart_id());

            if (!PointsUids.contains(l.getEnd_id()) && !l.getEnd_id().equals(points.getUid()))
                PointsUids.add(l.getEnd_id());
        }
        return App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.in(PointsUids)).build().list();
    }

    Marker poiMarker = null;
    Drawable drawable = null;

    //这里获取定位
    @Override
    public void onReceiveLocation(@NotNull ChineLocationBean chinaLocationBean) {
        high = chinaLocationBean.getChinaAltitude();
        address = chinaLocationBean.getChinaAddress();
        if (drawable == null) {
            drawable = getResources().getDrawable(R.drawable.yuandian);
        }
        //实时获取位置用户的.
        useLocation = new Location("");
        if (locationType) {
            HashMap<String, Double> wgs2GCJ = GCJ2WGS.INSTANCE.delta(chinaLocationBean.getChinaLatitude(), chinaLocationBean.getChinaLongitude());
            //double[] wgs2GCJ = GPSUtils.gcj2WGS(chinaLocationBean.getChinaLatitude(), chinaLocationBean.getChinaLongitude());
            useLocation.setLatitude (wgs2GCJ.get("lat"));
            useLocation.setLongitude(wgs2GCJ.get("lon"));
        }
        //判空，不然会报错
        //地球坐标系=>火星坐标系
        if (getInstances().btn_model) {//只有卫星模式才可以进行。
            double latitude = chinaLocationBean.getChinaLatitude();
            double longitude = chinaLocationBean.getChinaLongitude();
            HashMap<String, Double> wgs2GCJ = GCJ2WGS.INSTANCE.delta(chinaLocationBean.getChinaLatitude(), chinaLocationBean.getChinaLongitude());
            GeoPoint mapCenter = new GeoPoint(wgs2GCJ.get("lat"), wgs2GCJ.get("lon"));
            if (latitude > 0 && longitude > 0) {
                mapController = mMapView.getController();
                GeoPoint gps84 = new GeoPoint(mapCenter.getLatitude(),mapCenter.getLongitude());
                if (poiMarker != null && mMapView.getOverlays().contains(poiMarker)) {
                    mMapView.getOverlays().remove(poiMarker);
                    poiMarker = new Marker(mMapView);
                    poiMarker.setPosition(gps84);
                    poiMarker.setIcon(drawable);
                    poiMarker.setTitle("自己");
                    poiMarker.setId("myself");
                    poiMarker.setAnchor(0.19f, 0.12f);
                    poiMarker.setOnMarkerClickListener(new Marker.OnMarkerClickListener() {
                        @Override
                        public boolean onMarkerClick(Marker marker, MapView mapView) {
                            return false;
                        }
                    });
                    mMapView.getOverlays().add(poiMarker);
                } else {
                    poiMarker = new Marker(mMapView);
                    poiMarker.setPosition(gps84);
                    poiMarker.setIcon(drawable);
                    poiMarker.setTitle("自己");
                    poiMarker.setAnchor(0.19f, 0.12f);
                    poiMarker.setId("myself");
                    poiMarker.setOnMarkerClickListener(new Marker.OnMarkerClickListener() {
                        @Override
                        public boolean onMarkerClick(Marker marker, MapView mapView) {
                            return false;
                        }
                    });
                    mMapView.getOverlays().add(poiMarker);
                }
                //动画平移到当前位置
                mapController.animateTo(gps84, mMapView.getZoomLevelDouble(), 100L);
            }
        }
    }
}
